<?php
/**
 * IG_Filesystem_File
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: File.php 991 2011-11-02 06:42:40Z mmxie $
 */
class IG_Filesystem_File
{
    const UPLOAD_DIR = '/upload';

    public static function getFrontPath()
    {
        return APPLICATION_PATH . '/../public';
    }

    /**
     * 返回指定类型的文件，$type 可以是array或string
     *
     * @param string $path, the filepath to search
     * @param mixed $type, the file extension to return
     * @param string $appendPath, the path to append to the returned files
     */
    public static function getFilesByType($path, $type = false, $appendPath = false, $includeExtension = false)
    {
        if (is_dir($path)) {
            $dir = scandir($path); //open directory and get contents
            if (is_array($dir)) { //it found files
                $returnFiles = false;
                foreach ($dir as $file) {
                    if (! is_dir($path . '/' . $file)) {
                        if ($type) { //validate the type
                            $fileParts = explode('.', $file);
                            if (is_array($fileParts)) {
                                $c = count($fileParts) - 1; //arrays always start with 0
                                $fileType = $fileParts[$c];
                                //check whether the filetypes were passed as an array or string
                                if (is_array($type)) {
                                    if (in_array($fileType, $type)) {
                                        $filePath = $appendPath . $file;
                                        if ($includeExtension == true) {
                                            $filePath .= '.' . $fileType;
                                        }
                                        $returnFiles[] = $filePath;
                                    }
                                } else {
                                    if ($fileType == $type) {
                                        $filePath = $appendPath . $file;
                                        if ($includeExtension == true) {
                                            $filePath .= '.' . $fileType;
                                        }
                                        $returnFiles[] = $filePath;
                                    }
                                }
                            }
                        } else { //the type was not set.  return all files and directories
                            $returnFiles[] = $file;
                        }
                    }
                }
                if ($returnFiles) {
                    return $returnFiles;
                }
            }
        }
    }

    /**
     * creates a new file from a string
     *
     * @param string $path
     * @param string $content
     * @return string
     */
    public static function saveFile($path, $content, $type)
    {
        //$content = stripslashes($content);
        try {
            $file = fopen($path,$type);
            if (flock($file, LOCK_EX)) {
                fwrite($file,$content);
                flock($file,LOCK_UN);
            }
            fclose($file);
            return true;
        }
        catch (Zend_Exception $e) {
            return false;
        }
    }

    /**
     * rename the selected file
     *
     * @param string $source
     * @param string $newName
     */
    public static function rename($source, $newName)
    {
        if (file_exists($source)) {
            rename($source, $newName);
        }
    }

    /**
     * copy a file
     *
     * @param string $source
     * @param string $target
     * @return bool
     */
    public static function copy($source, $target)
    {
        if (file_exists($source)) {
            return copy($source, $target);
        }
    }

    /**
     * move a file
     *
     * @param string $source
     * @param string $target
     */
    public static function move($source, $target)
    {
        if (file_exists($source)) {
            rename($source, $target);
        }
    }

    /**
     * delete a file
     *
     * @param string $path
     */
    public static function delete($path)
    {
        @unlink($path);
    }

    /**
     * this function cleans up the filename
     * it strips ../ and ./
     * it spaces with underscores
     *
     * @param string $fileName
     */
    public static function cleanFilename($fileName)
    {
        $fileName = str_replace('../', '', $fileName);
        $fileName = str_replace('./', '', $fileName);
        $fileName = str_replace(' ', '_', $fileName);
        return $fileName;
    }

    public static function getFileExtension($filename)
    {
        if (! empty($filename)) {
            $fileparts = explode(".", $filename);
            if (is_array($fileparts)) {
                $index = count($fileparts) - 1;
                $extension = $fileparts[$index];
                return $extension;
            }
        }
        return null;
    }

    public static function isUploaded($key)
    {
        return isset($_FILES[$key]) && is_uploaded_file($_FILES[$key]['tmp_name']);
        /*
        if ($_FILES[$key] && ! empty($_FILES[$key]['tmp_name'])) {
            return true;is_uploaded_file()
        }*/
    }

    /**
     * you pass this function the key for the $_FILES[key] array
     * and the new filepath to move the file to
     * then add the new filename
     * if $createPath is true then this will attempt to create the directories required for the path
     *
     * @param string $key
     * @param string $path
     * @param string $filename
     * @param bool $createPath
     */
    public static function upload($key, $fullPath = null)
    {
        if (self::isUploaded($key)) {
            //default to the name on the client machine
            if (!$fullPath) {
                $path     = self::_getDateDir();
                $basename = explode('.', basename($_FILES[$key]['name']));
                $suffix   = end($basename);
                $fullPath = $path . time() . mt_rand(100, 999) . '.' . strtolower($suffix);
            }

            IG_Filesystem_Dir::mkdirs(dirname($fullPath));

            if (move_uploaded_file($_FILES[$key]['tmp_name'], $fullPath)) {
                return str_replace(
                    array(realpath(self::getFrontPath()), '\\'),
                    array('', '/'),
                    realpath($fullPath)
                );
            }
        }
    }

    protected static function _getDateDir()
    {
        return self::getFrontPath() . self::UPLOAD_DIR . date('/Ym/d/');
    }
}